//
//  HCConsoleView.m
//  HCToolBox
//
//  Created by Hotacool on 2019/3/20.
//

#import "HCConsoleView.h"
#import "HCScrollMenuBar.h"
#import "UIView+HCTB.h"
#import "HCUtilities.h"
#import "HCConsoleLogger.h"
#import "HCLogServer.h"
#import "UIControl+HCTB.h"
#import "HCFileLogger.h"
#import "HCConsoleCell.h"

static const CGFloat kMenuBarHeight = 30;
static const CGFloat kDragBarHeight = 1;
static const CGFloat kSearchBarHeight = 44.0;
//static const CGFloat klogTextFont = 12.0;
static NSString *const kCellId = @"cellid";

#define kDefaultInfoString @"点击启动按钮开启日志服务器"
#define kLogServerInfoString @"服务器已启动!\n请在浏览器中输入地址: \'%@log\' 以查看完整日志"
#define kDownloadString @"存储最新日志"

@interface _HCConsoleSearchBar : UIView <UITextFieldDelegate>

@property (nonatomic, strong, readonly) UITextField *searchTextField;
@property (nonatomic, strong, readonly) UIButton *clearBtn;
@property (nonatomic, strong, readonly) UIButton *addMarkerBtn;
@property (nonatomic, strong, readonly) UIButton *moveToBottomBtn;

@end

@interface _HCConsoleSystemView : UIView

@property (nonatomic, strong, readonly) UIButton *startBtn;
@property (nonatomic, strong, readonly) UILabel *infoLabel;
@property (nonatomic, strong, readonly) UIButton *downloadBtn;

@end

@interface HCConsoleView () <HCScrollMenuBarDelegate, UITableViewDelegate, UITableViewDataSource, UIDocumentInteractionControllerDelegate>
@property (nonatomic, strong) UIView *dragBar;
@property (nonatomic, strong) HCScrollMenuBar *categoryMenu;
@property (nonatomic, strong) HCScrollMenuBar *levelMenu;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) _HCConsoleSearchBar *searchBar;
@property (nonatomic, strong) _HCConsoleSystemView *systemView;
@property (nonatomic, strong) UIDocumentInteractionController *documentInteractionController;

@property (nonatomic, assign) DDLogFlag logFlag;
@property (nonatomic, copy) NSString *targetWords;
@property (nonatomic, copy, readonly) NSArray <DDLogMessage*>* messages;
@property (nonatomic, strong) NSMutableArray <DDLogMessage*>* filterMessages;
@end

@implementation HCConsoleView {
    HCConsoleLogger *_logger;
    NSInteger _verboseCount;//log总量，历史log数+新增log数
    HCLogServer *_logServer;
}

- (void)dealloc {
    [DDLog removeLogger:_logger];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setUp];
        //datas
        _logFlag = DDLogFlagVerbose;
        _targetWords = nil;
        _filterMessages = [NSMutableArray array];
        //initail logger
        _logger = [HCConsoleLogger new];
        [DDLog addLogger:_logger];
        _logger.maxMessages = 1024;
        HCFileLogger *fileLogger = [[HCFileLogger alloc] init];
        [DDLog addLogger:fileLogger];
        @weakIt(self);
        [_logger subscribNext:^(NSArray<DDLogMessage *> *logArray) {
            dispatch_async(dispatch_get_main_queue(), ^{
                @strongIt(self)
                if (!self.isHidden && !self.tableView.isHidden) {
                    [self updateWithComingLogs:logArray];
                }
            });
        }];
    }
    return self;
}

- (void)setHidden:(BOOL)hidden {
    [super setHidden:hidden];
    if (!hidden  && !self.tableView.isHidden) {
        [self updateWithComingLogs:nil];
    }
}

- (void)setUp {
    [self addSubview:self.dragBar];
    [self addSubview:self.categoryMenu];
    [self addSubview:self.levelMenu];
    [self addSubview:self.tableView];
    [self addSubview:self.searchBar];
    [self addSubview:self.systemView];
    self.systemView.hidden = YES;
    
    @weakIt(self);
    [self.searchBar.searchTextField addActionBlock:^(id _Nonnull sender) {
        @strongIt(self);
        self.targetWords = self.searchBar.searchTextField.text;
        [self filterMessageWithLogFlag:self.logFlag targetWords:self.targetWords];
        [self.tableView reloadData];
    } forControlEvents:UIControlEventEditingChanged];

    [self.searchBar.moveToBottomBtn addActionBlock:^(id _Nonnull sender) {
        @strongIt(self);
        if (self.tableView.contentSize.height - self.tableView.height > 0) {
            [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height - self.tableView.height) animated:YES];
        }
    } forControlEvents:UIControlEventTouchUpInside];

    [self.searchBar.clearBtn addActionBlock:^(id _Nonnull sender) {
        @strongIt(self);
        [self->_logger clear];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self filterMessageWithLogFlag:self.logFlag targetWords:self.targetWords];
            [self.tableView reloadData];
        });
    } forControlEvents:UIControlEventTouchUpInside];

    [self.searchBar.addMarkerBtn addActionBlock:^(id _Nonnull sender) {
        @strongIt(self);
        DDLogMessage *marker = [DDLogMessage new];
        marker->_flag = 1001;
        marker->_timestamp = [NSDate date];
        marker->_message = @"=========Marker=========";
        [self.filterMessages addObject:marker];
        [self.tableView reloadData];
        [self.tableView layoutIfNeeded];
        if (self.tableView.contentSize.height - self.tableView.height > 0) {
            [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height - self.tableView.height) animated:YES];
        }
    } forControlEvents:UIControlEventTouchUpInside];

    [self.systemView.startBtn addActionBlock:^(id _Nonnull sender) {
        @strongIt(self);
        if (!self->_logServer) {
            self->_logServer = [[HCLogServer alloc] initWithLogger:self->_logger];
        }
        if (self->_logServer.isRunning) {
            [self->_logServer stopServer];
        } else {
            [self->_logServer startServerWithPort:8081];
        }
        @weakIt(self);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongIt(self);
            if (self->_logServer.isRunning) {
                self.systemView.infoLabel.text = [NSString stringWithFormat:kLogServerInfoString, self->_logServer.serverURL];
                [self.systemView.startBtn setTitle:@"停止" forState:UIControlStateNormal];
            } else {
                self.systemView.infoLabel.text = kDefaultInfoString;
                [self.systemView.startBtn setTitle:@"启动" forState:UIControlStateNormal];
            }
        });
    } forControlEvents:UIControlEventTouchUpInside];
    
    [self.systemView.downloadBtn addActionBlock:^(id _Nonnull sender) {
        @strongIt(self);
        NSArray *fileNames = [HCFileLogger logFiles];
        if (fileNames.count < 1) {
            return;
        }
        NSString *filename = fileNames.firstObject;
        NSString *localPath = [[HCFileLogger logsDirectory] stringByAppendingPathComponent:filename];
        if (localPath.length == 0) {
            return;
        }
        NSURL *pathUrl = [[NSURL alloc]initFileURLWithPath:localPath];

        // Initialize Document Interaction Controller
        self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:pathUrl];

        // Configure Document Interaction Controller
        [self.documentInteractionController setDelegate:self];

        // Present Open In Menu
        [self.documentInteractionController presentOptionsMenuFromRect:[self.systemView.downloadBtn frame] inView:self.systemView animated:YES];
       } forControlEvents:UIControlEventTouchUpInside];
}

- (void)layoutSubviews {
    self.dragBar.frame = CGRectMake(0, 0, self.width, kDragBarHeight);
    self.categoryMenu.frame = CGRectMake(0, CGRectGetMaxY(self.dragBar.frame), self.width, kMenuBarHeight);
    self.levelMenu.frame = hcSetRectY(self.categoryMenu.frame, CGRectGetMaxY(self.categoryMenu.frame));
    CGFloat y = self.height - kSearchBarHeight - self.hctb_safeAreaInsets.bottom;
    self.searchBar.frame = CGRectMake(0, y, self.width, kSearchBarHeight);
    CGFloat h = CGRectGetMinY(self.searchBar.frame) - CGRectGetMaxY(self.levelMenu.frame);
    self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.levelMenu.frame), self.width, h);
    self.systemView.frame = hcSetRectHeight(self.levelMenu.frame, self.height-CGRectGetMaxY(self.categoryMenu.frame));
}

- (UIView *)dragBar {
    if (!_dragBar) {
        _dragBar = [[UIView alloc] init];
        _dragBar.backgroundColor = hcRGB_HEX(0xF5F5F5);
    }
    return _dragBar;
}

- (HCScrollMenuBar *)categoryMenu {
    if (!_categoryMenu) {
        _categoryMenu = [[HCScrollMenuBar alloc] initWithItemArray:@[@"Log",/** @"Monitor", **/@"System"]];
        _categoryMenu.delegate = self;
        _categoryMenu.backgroundColor = hcRGB_HEX(0xF5F5F5);
        _categoryMenu.titleColorNormal = hcRGB_HEX(0x606060);
        _categoryMenu.titleColorSelect = hcRGB_HEX(0xEC2E31);;
        _categoryMenu.titleBackgroundColorSelect = [UIColor whiteColor];
        _categoryMenu.indicatorColor = [UIColor clearColor];
        _categoryMenu.titleFontNormal = [UIFont systemFontOfSize:14.0];
    }
    return _categoryMenu;
}

- (HCScrollMenuBar *)levelMenu {
    if (!_levelMenu) {
        _levelMenu = [[HCScrollMenuBar alloc] initWithItemArray:@[@"Verbose", @"Debug", @"Info", @"Warn", @"Error"]];
        _levelMenu.delegate = self;
        _levelMenu.backgroundColor = hcRGB_HEX(0xF5F5F5);
        _levelMenu.titleColorNormal = hcRGB_HEX(0x606060);
        _levelMenu.titleColorSelect = hcRGB_HEX(0xEC2E31);
        _levelMenu.titleBackgroundColorSelect = [UIColor whiteColor];
        _levelMenu.indicatorColor = [UIColor clearColor];
        _levelMenu.titleFontNormal = [UIFont systemFontOfSize:14.0];
    }
    return _levelMenu;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 200;
        _tableView.rowHeight=UITableViewAutomaticDimension;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
    }
    return _tableView;
}

- (_HCConsoleSearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[_HCConsoleSearchBar alloc] init];
    }
    return _searchBar;
}

- (_HCConsoleSystemView *)systemView {
    if (!_systemView) {
        _systemView = [[_HCConsoleSystemView alloc] init];
        _systemView.infoLabel.text = kDefaultInfoString;
    }
    return _systemView;
}

- (NSArray<DDLogMessage *> *)messages {
    return _logger.logMessages;
}

- (UITextField *)searchTextField {
    return self.searchBar.searchTextField;
}

#pragma mark - log tableview
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    return YES;
}

- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    // 复制对应cell的log到剪贴板
    DDLogMessage *logMessage;
    if (indexPath.row < self.filterMessages.count) {
        logMessage = self.filterMessages[indexPath.row];
    }
    [UIPasteboard generalPasteboard].string = [self textForLog:logMessage];
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    DDLogMessage * logMessage;
//    if (indexPath.row < self.filterMessages.count) {
//        logMessage = self.filterMessages[indexPath.row];
//    }
//    if (hcObjectIsEmpty(logMessage.message)) {
//        return 34;
//    } else {
//        CGRect rect = [[self textForLog:logMessage] boundingRectWithSize:CGSizeMake(self.tableView.width, MAXFLOAT)
//                                                       options:NSStringDrawingUsesLineFragmentOrigin
//                                                    attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:klogTextFont]}
//                                                       context:nil];
//        return rect.size.height;
//    }
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.filterMessages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HCConsoleCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    if (!cell) {
        cell = [[HCConsoleCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:kCellId];
    }
    DDLogMessage * logMessage;
    if (indexPath.row < self.filterMessages.count) {
        logMessage = self.filterMessages[indexPath.row];
    }
    if (logMessage) {
        switch (logMessage->_flag) {
            case DDLogFlagError   : {
                cell.textLB.textColor = [UIColor redColor];
                break;
            }
            case DDLogFlagWarning : {
                cell.textLB.textColor = [UIColor orangeColor];
                break;
            }
            case DDLogFlagInfo    : {
                cell.textLB.textColor = [UIColor greenColor];
                break;
            }
            case DDLogFlagDebug   : {
                cell.textLB.textColor = [UIColor whiteColor];
                break;
            }
            case 1001: {//marker
                cell.textLB.textColor = [UIColor yellowColor];
                break;
            }
            default               : {
                cell.textLB.textColor = [UIColor lightGrayColor];
                break;
            }
        }
        cell.textLB.text = [self textForLog:logMessage];
    }
    return cell;
}

- (NSString*)textForLog:(DDLogMessage*)log {
    NSString * prefix;
    switch (log->_flag) {
        case DDLogFlagError   : prefix = @"Ⓔ"; break;
        case DDLogFlagWarning : prefix = @"Ⓦ"; break;
        case DDLogFlagInfo    : prefix = @"Ⓘ"; break;
        case DDLogFlagDebug   : prefix = @"Ⓓ"; break;
        default               : prefix = @"Ⓥ"; break;
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
    dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT+0800"];
    return [NSString stringWithFormat:@"%@ %@ %@", prefix, [dateFormatter stringFromDate:log.timestamp], log.message];
}

- (void)updateWithComingLogs:(NSArray<DDLogMessage *> *)logArray {
    BOOL isBottom = NO;//底部添加新数据时，tableview保持滚动到最底部
    NSInteger totalRows = [self.tableView numberOfRowsInSection:0];
    if (self.tableView.indexPathsForVisibleRows.lastObject.row == totalRows - 1) {
        isBottom = YES;
    }
    NSMutableArray <NSIndexPath*>* indexpathArray = [NSMutableArray array];
    __block NSInteger lastIndex = [self.tableView numberOfRowsInSection:0] - 1;
    _verboseCount += logArray.count;
    if (_verboseCount != self.messages.count) {//因为HCConsoleLogger有历史数据，新增indexpathArray会与实际显示数据self.messages不一致
        _verboseCount = self.messages.count;
        [self filterMessageWithLogFlag:self.logFlag targetWords:self.targetWords];//全量更新
        [self.tableView reloadData];
    } else {
        [logArray enumerateObjectsUsingBlock:^(DDLogMessage * _Nonnull log, NSUInteger idx, BOOL * _Nonnull stop) {
            if (log->_flag == self.logFlag || self.logFlag == DDLogFlagVerbose) {
                if (hcObjectIsEmpty(self.targetWords)) {
                    [self.filterMessages addObject:log];
                    [indexpathArray addObject:[NSIndexPath indexPathForRow:++lastIndex inSection:0]];
                } else if ([log.message.lowercaseString containsString:self.targetWords.lowercaseString]) {
                    [self.filterMessages addObject:log];
                    [indexpathArray addObject:[NSIndexPath indexPathForRow:++lastIndex inSection:0]];
                }
            }
        }];
        if (!hcObjectIsEmpty(indexpathArray)) {
            [self.tableView insertRowsAtIndexPaths:indexpathArray withRowAnimation:UITableViewRowAnimationFade];
        }
    }
    if (isBottom && self.tableView.contentSize.height - self.tableView.height > 0) {
        [self.tableView layoutIfNeeded];
        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height - self.tableView.height) animated:YES];
    }
}
#pragma mark - menubar
- (void)scrollMenuBar:(HCScrollMenuBar *)scrollMenuBar selectAtIndex:(NSInteger)index {
    if (scrollMenuBar == self.categoryMenu) {
        switch (index) {
            case 0: {
                self.tableView.hidden = NO;
                self.levelMenu.hidden = NO;
                self.searchBar.hidden = NO;
                self.systemView.hidden = YES;
                [self updateWithComingLogs:nil];
                break;
            }
//            case 1: {
//                self.tableView.hidden = YES;
//                self.levelMenu.hidden = YES;
//                self.searchBar.hidden = YES;
//                self.systemView.hidden = YES;
//                break;
//            }
            case 1: {
                self.tableView.hidden = YES;
                self.levelMenu.hidden = YES;
                self.searchBar.hidden = YES;
                self.systemView.hidden = NO;
                break;
            }
            
        }
    }
    if (scrollMenuBar == self.levelMenu) {
        DDLogFlag flag = DDLogFlagVerbose;
        switch (index) {
            case 0: flag = DDLogFlagVerbose; break;
            case 1: flag = DDLogFlagDebug; break;
            case 2: flag = DDLogFlagInfo; break;
            case 3: flag = DDLogFlagWarning; break;
            case 4: flag = DDLogFlagError; break;
        }
        _verboseCount = self.messages.count;
        [self filterMessageWithLogFlag:flag targetWords:self.targetWords];
        [self.tableView reloadData];
    }
}

- (void)filterMessageWithLogFlag:(DDLogFlag)flag targetWords:(NSString*)targetWords {
    [self.filterMessages removeAllObjects];
    void(^filterMessageBlk)(DDLogFlag) = ^(DDLogFlag flag) {
        [self.messages enumerateObjectsUsingBlock:^(DDLogMessage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj->_flag == flag || flag == DDLogFlagVerbose) {
                if (hcObjectIsEmpty(targetWords)) {
                    [self.filterMessages addObject:obj];
                } else if ([obj.message.lowercaseString containsString:targetWords.lowercaseString]) {
                    [self.filterMessages addObject:obj];
                }
            }
        }];
    };
    filterMessageBlk(flag);
    self.logFlag = flag;
}

@end

@implementation _HCConsoleSearchBar
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setUp];
    }
    return self;
}

- (void)setUp {
    _moveToBottomBtn = [UIButton new];
    [_moveToBottomBtn setTitle:@"滑到\n底部" forState:0];
    [_moveToBottomBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _moveToBottomBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    _moveToBottomBtn.titleLabel.minimumScaleFactor = 0.5;
    _moveToBottomBtn.titleLabel.numberOfLines = 2;
    [_moveToBottomBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    _moveToBottomBtn.titleLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
//    [_moveToBottomBtn setImage:[HCUtilities imageWithName:@"angle_down"] forState:UIControlStateNormal];
    [self addSubview:_moveToBottomBtn];
    
    _addMarkerBtn = [UIButton new];
//    [_addMarkerBtn setImage:[HCUtilities imageWithName:@"add"] forState:UIControlStateNormal];
    [_addMarkerBtn setTitle:@"添加\n标记" forState:0];
    [_addMarkerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _addMarkerBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    _addMarkerBtn.titleLabel.minimumScaleFactor = 0.5;
    _addMarkerBtn.titleLabel.numberOfLines = 2;
    _addMarkerBtn.titleLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
    [_addMarkerBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [self addSubview:_addMarkerBtn];
    
    _clearBtn = [UIButton new];
//    [_clearBtn setImage:[HCUtilities imageWithName:@"delete"] forState:UIControlStateNormal];
    [_clearBtn setTitle:@"清空" forState:0];
    [_clearBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _clearBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    _clearBtn.titleLabel.minimumScaleFactor = 0.5;
    _clearBtn.titleLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
    [_clearBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [self addSubview:_clearBtn];
    
    _searchTextField = [[UITextField alloc] init];
    _searchTextField.backgroundColor = [UIColor clearColor];
    _searchTextField.delegate = self;
    _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _searchTextField.tintColor = [UIColor whiteColor];
    _searchTextField.textColor = _searchTextField.tintColor;
    _searchTextField.font = [UIFont systemFontOfSize:14];
    //下行代码会导致IOS13+系统使用暗黑模式，需注释
    //_searchTextField.keyboardAppearance = UIKeyboardAppearanceDark;
    _searchTextField.returnKeyType = UIReturnKeyDone;
    _searchTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _searchTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    _searchTextField.layer.borderWidth = 0.5;
    _searchTextField.layer.borderColor = [[UIColor whiteColor] colorWithAlphaComponent:.8].CGColor;
    _searchTextField.layer.cornerRadius = 3;
    _searchTextField.placeholder = @"输入要筛选的日志";
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:_searchTextField.placeholder attributes:@{NSForegroundColorAttributeName:[[UIColor whiteColor] colorWithAlphaComponent:0.8], NSFontAttributeName:_searchTextField.font }];
    _searchTextField.attributedPlaceholder = attrString;
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, self.height)];
    leftView.backgroundColor = [UIColor clearColor];
    _searchTextField.leftView = leftView;
    _searchTextField.leftViewMode = UITextFieldViewModeAlways;
    
    [self addSubview:_searchTextField];
}

- (void)layoutSubviews {
    self.moveToBottomBtn.frame = CGRectMake(0, 0, 40, self.height);
    self.addMarkerBtn.frame = hcSetRectX(self.moveToBottomBtn.frame, CGRectGetMaxX(self.moveToBottomBtn.frame));
    self.clearBtn.frame = hcSetRectX(self.moveToBottomBtn.frame, self.width - 40);
    CGFloat width = CGRectGetMinX(self.clearBtn.frame) - CGRectGetMaxX(self.addMarkerBtn.frame);
    self.searchTextField.frame = CGRectMake(CGRectGetMaxX(self.addMarkerBtn.frame), 0, width, CGRectGetHeight(self.moveToBottomBtn.frame));
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.searchTextField resignFirstResponder];
    return NO;
}
@end

@implementation _HCConsoleSystemView
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setUp];
    }
    return self;
}

- (void)setUp {
    _startBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 34)];
    _startBtn.layer.cornerRadius = 4;
    _startBtn.backgroundColor = [UIColor grayColor];
    [_startBtn setTitle:@"启动" forState:UIControlStateNormal];
    [_startBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self addSubview:_startBtn];
    
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = [UIColor clearColor];
    bgView.layer.borderColor = [UIColor whiteColor].CGColor;
    bgView.layer.borderWidth = 0.5;
    bgView.layer.cornerRadius = 4;
    bgView.tag = 100;
    [self addSubview:bgView];
    
    _infoLabel = [[UILabel alloc] init];
    _infoLabel.numberOfLines = 0;
    _infoLabel.font = [UIFont systemFontOfSize:14];
    _infoLabel.textColor = [UIColor whiteColor];
    [bgView addSubview:_infoLabel];
    
    
    _downloadBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 150, 34)];
    _downloadBtn.layer.cornerRadius = 4;
    _downloadBtn.backgroundColor = [UIColor grayColor];
    [_downloadBtn setTitle:kDownloadString forState:UIControlStateNormal];
    [_downloadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self addSubview:_downloadBtn];
    
}

- (void)layoutSubviews {
    self.startBtn.frame = hcSetRectXY(self.startBtn.frame, 4, 4);
    self.downloadBtn.frame = hcSetRectXY(self.downloadBtn.frame, CGRectGetMaxX(self.startBtn.frame)+4, 4);
    UIView *bgView = [self viewWithTag:100];
    bgView.frame = CGRectMake(4, CGRectGetMaxY(self.startBtn.frame)+8, self.width-8, 100);
    _infoLabel.frame = CGRectMake(8, 8, bgView.width-8*2, bgView.height-8*2);
}
@end
